package com.dkd.http.controller;

import cn.elegent.ac.ElegentAC;
import cn.elegent.iu.annotation.ElegentIU;
import cn.elegent.pay.ElegentPay;
import cn.elegent.pay.dto.PayRequest;
import cn.elegent.pay.dto.PayResponse;
import com.dkd.contract.OrderCheck;
import com.dkd.service.ESOrderService;
import com.dkd.service.OrderService;
import com.dkd.vo.OrderVO;
import com.dkd.vo.Pager;
import com.dkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 订单
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ElegentPay elegentPay;
	
	@Autowired
	private ElegentAC elegentAC;
	
	@Autowired
	private ESOrderService esOrderService;
	
	/**
	 * 支付
	 * @param payVO
	 * @return
	 */
	@PostMapping("/requestPay/{tradeType}/{platform}")
	@ElegentIU
	public PayResponse requestPay(@RequestBody PayVO payVO, @PathVariable("tradeType") String tradeType, @PathVariable("platform") String platform) {
		//调用本地订单系统 , 创建订单
		var orderEntity = orderService.createOrder(payVO, platform);
		//封装支付请求对象调用支付
		var param = new PayRequest();
		param.setBody(orderEntity.getSkuName());//商品名称
		param.setOrderSn(orderEntity.getOrderNo());//订单编号
		param.setTotalFee(orderEntity.getAmount().intValue());//订单金额
		param.setOpenid(payVO.getOpenId());//openid
		
		//发送延迟消息---------
		var orderCheck = new OrderCheck();
		orderCheck.setOrderNo(orderEntity.getOrderNo());
		try {
			//elegentAC.publish("$delayed/300/" + TopicConfig.ORDER_CHECK_TOPIC, orderCheck);
		} catch (Exception e) {
			log.error("send to emq error", e);
		}
		
		return elegentPay.requestPay(param, tradeType, platform);
	}
	
	/**
	 * 获取openId
	 * @param jsCode
	 * @return
	 */
	@GetMapping("/openid/{jsCode}")
	public String getOpenid(@PathVariable("jsCode") String jsCode) {
		return elegentPay.getOpenid(jsCode, "wxpay");
	}
	
	
	/**
	 * 订单查询
	 * @param pageIndex
	 * @param pageSize
	 * @param orderNo
	 * @param openId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@GetMapping("/search")
	public Pager<OrderVO> search(
			@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(value = "orderNo", required = false, defaultValue = "") String orderNo,
			@RequestParam(value = "openId", required = false, defaultValue = "") String openId,
			@RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
			@RequestParam(value = "endDate", required = false, defaultValue = "") String endDate) {
		
		return esOrderService.search(pageIndex, pageSize, orderNo, openId, startDate, endDate);
	}
}